package com.example.beat_x3.Fragments;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.beat_x3.Adapter.MyInstrumentAdapter;
import com.example.beat_x3.Client.GetResult;
import com.example.beat_x3.R;

import Entity.Equipments;
import Entity.Inf;

public class MyInstrumentFragment extends MyFragment {
    public MyInstrumentAdapter myInstrumentAdapter;
    boolean isRefresh = false;
    public Handler myHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                myInstrumentAdapter.refresh();
            } else if (msg.what == 1) {
                myInstrumentAdapter.change();
                isRefresh = true;
            } else {
                myInstrumentAdapter.delete();
                isRefresh = true;
            }
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_myinstrument, null);
        RecyclerView recyclerView = view.findViewById(R.id.myi_re);
        recyclerView.setLayoutManager(new LinearLayoutManager(Inf.context));
        myInstrumentAdapter = new MyInstrumentAdapter();
        recyclerView.setAdapter(myInstrumentAdapter);
        view.findViewById(R.id.myi_backbutton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRefresh) {
                    Inf.instrumentFragment.refresh();
                    isRefresh = false;
                }
                changeFragment(Inf.instrumentFragment);
            }
        });
        new MyInstrumentThread().start();
        return view;
    }

    class MyInstrumentThread extends Thread {
        @Override
        public void run() {
            Equipments res = GetResult.QueryEquipments(1, Inf.stuInf.StudentAccount);
            if (res != null) {
                myInstrumentAdapter.equipments = res.equipments;
                myHandler.sendEmptyMessage(0);
            }
        }
    }
}
